/*
 * @Description:
 * @Version:
 * @Autor: tangwc
 * @Date: 2023-05-02 22:11:12
 * @LastEditors: tangwc
 * @LastEditTime: 2023-06-22 16:50:18
 * @FilePath: \esp32_lvgl_V7.11_demo\components\lvgl_esp32_drivers\lvgl_touch\cst816t.c
 *
 *  Copyright (c) 2023 by tangwc, All Rights Reserved.
 */
#include <stdio.h>
#include "driver/i2c.h"
#include "cst816t.h"
#include "esp_log.h"
#include "lvgl_i2c_conf.h"
#include "esp_system.h"
#include "esp_log.h"
#include <stddef.h>

/*********************
 *      DEFINES
 *********************/
#define TAG "CST816T"
#define CST816T_ADDR 0X15

esp_err_t cst816t_read_len(uint8_t reg_addr, uint8_t *data, uint8_t len)
{
    esp_err_t res = 0;
    res = i2c_master_write_read_device(TOUCH_I2C_PORT, CST816T_ADDR, &reg_addr, 1, data, len, 1000 / portTICK_PERIOD_MS);

    return res;
}

uint8_t cst816t_chipId(void)
{
    uint8_t id = 0;
    uint8_t res = 0;
    res = cst816t_read_len(0xA7, &id, 1);

    ESP_LOGI(TAG, "touch chip: CST816T======%d===========%d", id, res);

    return 0;
}

static esp_err_t cst816t_get_touch_points_num(uint8_t *touch_points_num)
{
    uint8_t res = 0;
    res = cst816t_read_len(0x02, touch_points_num, 1);
    return res;
}

static esp_err_t cst816t_read_pos(uint8_t *touch_points_num, uint16_t *x, uint16_t *y)
{
    uint8_t data[4];

    cst816t_get_touch_points_num(touch_points_num);
    // ESP_LOGI(TAG, "touch_points_num:%d\n", *touch_points_num);
    if (0 == *touch_points_num)
    {
        *x = 0;
        *y = 0;
        return 1;
    }
    else
    {
        cst816t_read_len(0x03, data, 4);

        *x = ((data[0] & 0x0f) << 8) | data[1];
        *y = ((data[2] & 0x0f) << 8) | data[3];

        ESP_LOGI(TAG, "pos:===========X:%d==========Y:%d", *x, *y);
    }
    return ESP_OK;
}

/**
 * Get the current position and state of the touchpad
 * @param data store the read data here
 * @return false: because no more data to be read
 */
bool cst816t_read(lv_indev_drv_t *drv, lv_indev_data_t *data)
{
    static uint8_t tp_num = 0;
    static uint16_t x = 0, y = 0;
    // 返回触摸位置
    cst816t_read_pos(&tp_num, &x, &y);

    if (0 == tp_num)
    {
        data->state = LV_INDEV_STATE_REL;
    }
    else
    {
        /* Swap xy order and invert y direction */
        data->point.x = x;
        data->point.y = y; // LV_VER_RES_MAX - x - 1;
        data->state = LV_INDEV_STATE_PR;
    }

    return false;
}